package com.gz.servlet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = "/db",initParams = {
        @WebInitParam(name="username",value = "gz"),
        @WebInitParam(name="password",value = "123456")  //initParams也可以在web.xml里面配置
})
public class DBServlet extends HttpServlet {

    public void init(ServletConfig config) throws ServletException {
        System.out.println("DBServlet init");
        super.init(config);//如果不写这个，则无法使用config ，报错404
                            // 如果不重写，默认有这个
                            //如果要重写，一定要写super.init(config);
    }


    public void doPost(HttpServletRequest request, HttpServletResponse response){

        //在DBServlet执行doPost/doGet 时，会获取到web.xml配置的用户名和密码
        //HttpServlet的父类GenericServlet有getServletConfig()方法
        //获取private transient ServletConfig config;
        //当一个属性被transient修饰，表示该属性不会被串行化，即不会被保存到文件，起到保密作用
        ServletConfig servletConfig = getServletConfig();
        String username = servletConfig.getInitParameter("username");
        String password = servletConfig.getInitParameter("password");
        System.out.println("初始化参数 username: "+username);
        System.out.println("初始化参数 password: "+password);
    }
    public void doGet(HttpServletRequest request, HttpServletResponse response){
        doPost(request, response);
    }
}
